Fill in the blanks in the code. What logic is missing?
- First, add the new element to the end of the list.
- The
whileloop must check two conditions to decide if it should continue bubbling up. - Inside the loop, swap the current element with its parent.
- After swapping, update the current element's index to its parent's index to continue moving up the tree.
heap_operations.py
def bubble_up(heap, index):
parent_index = (index - 1) // 2
# While not root and child > parent
while /* TODO: Loop condition */:
# Swap child and parent
/* TODO: Swap logic */
# Move up to the parent's position
/* TODO: Update index */
parent_index = (index - 1) // 2
def insert(heap, value):
# Step 1: Add element to the end
/* TODO: Add element */
# Step 2: Bubble it up to restore heap property
bubble_up(heap, len(heap) - 1)